import numpy as np
import re
import os
def start_analysis(control_params):
    result_path=control_params["result_path"]
    print(f"##### Start analysis of {result_path} #####")
    # =======================聚类结果逐个呈现====================================
    ballistic_npz_file = np.load(f"{result_path}/internal_ballistic.npz")
    r2_list=ballistic_npz_file['r2_list']
    
    optimization_npz_file = np.load(f"{result_path}/Optimization.npz")
    R_list=optimization_npz_file['R']
    R_list_Long=np.array(R_list)
    num=len(R_list_Long)
    R_list=[R_list[0],R_list[-1]]
    rb_list=optimization_npz_file['r_ref']
    rb_list=[rb_list[0],rb_list[-1]]
    eta_list=optimization_npz_file['loading_fraction']
    eta_list=[eta_list[0],eta_list[-1]]

    png_files=[]
    L_list=[]
    for i in range(num):
        try:
            png_file = [f for f in os.listdir(result_path) if f.startswith(f"{i}#") and f.endswith(".png")][0]
            png_files.append(png_file)

            match = re.search(r'L(\d+)', png_file)
            L_value = int(match.group(1))*0.001*R_list_Long[i]
            L_list.append(L_value)
        except:
            continue
        
    png_files=[png_files[0],png_files[-1]]
    L_list=[L_list[0],L_list[-1]]


    # ================生成分析报告并保存为 md 文件============================
    markdown_report_path = f"{result_path}/analysis_report.md"
    with open(markdown_report_path, 'w') as md_file:  
        # 结果展示部分
        md_file.write("### 优化结果展示\n\n")
        for idx in range(2):
            md_file.write(f"#### 序号 {idx} \n")
            md_file.write(f"见:(../{png_files[idx]})\n")
            formatted_L = "{0:.4g}".format(L_list[idx]*1000)
            md_file.write(f"L= {formatted_L} mm\n")
            formatted_R = "{0:.3g}".format(R_list[idx]*1000)
            md_file.write(f"R= {formatted_R} mm\n")
            formatted_rb="{0:.3g}".format(rb_list[idx]*1000)
            md_file.write(f"rb= {formatted_rb} mm/s\n")
            formatted_r2="{0:.4g}".format(r2_list[idx])
            md_file.write(f"r2= {formatted_r2}\n")
            formatted_eta = "{0:.3g}".format(eta_list[idx]*100)
            md_file.write(f"eta= {formatted_eta} %\n\n")
        
        md_file.write("### 性能提升量\n\n")
        formatted_r2_improve="{0:.3g}".format((r2_list[1]-r2_list[0])/r2_list[0]*100)
        md_file.write(f"r2 improve {formatted_r2_improve} %\n")
        formatted_eta_improve="{0:.3g}".format((eta_list[1]-eta_list[0])/eta_list[0]*100)
        md_file.write(f"eta improve {formatted_eta_improve} %\n")

    print(f"Markdown格式的分析报告已保存至 {markdown_report_path}")

if __name__ == "__main__":
    from OPT.Config import *
    define =make_define("dicA",0,0.001,"LGA","Samples_clustered")
    control_params, dead_dic = get_control_params(define, False)

    start_analysis(control_params)